package util;

import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by gulx@neusoft.com on 2018/3/7.
 */
public class ConcurrentUtil {

    final  int DEFAULT_POOL_SIZE = 10;
    final String DEFAULT_POOL_NAME = "DEFAULT_WORKER_THREAD-%d";
    /** 线程运行后是否可自动退出：true 退出，false 不退出
     * the JVM shuts down if there are only daemon threads running. */
    final  boolean DEFAULT_DAEMON = true;

    BasicThreadFactory factory;

    public static ConcurrentUtil instance = new ConcurrentUtil();

    public BasicThreadFactory getFactory(){
        return factory;
    }

    public  ListeningExecutorService getService(){
        return getService(DEFAULT_POOL_NAME,DEFAULT_POOL_SIZE,DEFAULT_DAEMON);
    }

    public  ListeningExecutorService getService(int poolSize){
        return MoreExecutors.listeningDecorator(getExecutorService(DEFAULT_POOL_NAME,poolSize,DEFAULT_DAEMON));
    }

    public  ListeningExecutorService getService(String name, int poolSize, boolean exit){
        return MoreExecutors.listeningDecorator(getExecutorService(name,poolSize,exit));
    }

    private ExecutorService getExecutorService(String name, int poolSize, boolean exit){
        factory = getBasicThreadFactory(name,exit);
        return new ThreadPoolExecutor(
                poolSize,
                poolSize,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(),
                factory,
                new ThreadPoolExecutor.AbortPolicy()
        );
    }

    private  BasicThreadFactory getBasicThreadFactory(String name, boolean exit){
        return new BasicThreadFactory.Builder()
                .namingPattern(name)
                .daemon(exit)
                .build();
    }
}

